<template>
  <div v-if="formState" class="security-config">
    <div class="transmission">
      <Form
        :model="formState"
        style="width: 1010px"
        :label-col="{ style: { width: '210px' } }"
        :wrapper-col="{ span: 16 }"
        autocomplete="off"
        label-align="right"
        :colon="false"
      >
        <FormItem
          name="JE_SYS_ENCRYPT"
          class="JE_SYS_ENCRYPT interval"
          :label="$t('safety.transmission')"
        >
          <Select
            v-model="formState.JE_SYS_ENCRYPT"
            :allow-clear="false"
            :default-value="formState.JE_SYS_ENCRYPT"
            :options="selectList"
            class="myInput"
            @change="(e) => handleChange(e, 'JE_SYS_ENCRYPT')"
          >
          </Select>
          <div class="text">
            <i>{{ $t('safety.transmissionTip') }}</i>
          </div>
        </FormItem>
        <FormItem
          name="JE_SYS_ENCRYPT_FIELD"
          class="JE_SYS_ENCRYPT_FIELD"
          :label="$t('safety.parameter')"
          v-bind="validateInfos['JE_SYS_ENCRYPT_FIELD']"
        >
          <TextArea
            v-model:value="formState.JE_SYS_ENCRYPT_FIELD"
            :rows="4"
            style="height: 90px; width: 700px"
            :style="{ resize: 'none' }"
            :class="{
              ['active']: formState.JE_SYS_ENCRYPT == '1' && !formState.JE_SYS_ENCRYPT_FIELD.trim(),
            }"
          ></TextArea>
          <div class="text">
            <i>{{ $t('safety.parameterTip') }}</i>
          </div>
        </FormItem>
        <FormItem
          name="JE_SYS_ENCRYPT_KEY1"
          class="JE_SYS_ENCRYPT_KEY1"
          :label="$t('safety.secretKey')"
        >
          <Input
            v-model:value="formState.JE_SYS_ENCRYPT_KEY1"
            disabled="disabled"
            class="myInput"
          />
          <div class="text">
            <i>{{ $t('safety.secretKeyTip') }}</i>
          </div>
        </FormItem>
        <!-- <FormItem
          name="JE_SYS_ENCRYPT_KEY2"
          class="JE_SYS_ENCRYPT_KEY2"
          :label="$t('safety.secretKey') + '2'"
        >
          <Input
            v-model:value="formState.JE_SYS_ENCRYPT_KEY2"
            disabled="disabled"
            class="myInput"
          />
          <div class="text">
            <i>{{ $t('safety.secretKeyTip') + '2' }}</i>
          </div>
        </FormItem> -->
        <!-- <FormItem
          name="JE_SYS_ENCRYPT_KEY3"
          class="JE_SYS_ENCRYPT_KEY3"
          :label="$t('safety.secretKey') + '3'"
        >
          <Input
            v-model:value="formState.JE_SYS_ENCRYPT_KEY3"
            disabled="disabled"
            class="myInput"
          />
          <div class="text">
            <i>{{ $t('safety.secretKeyTip') + '3' }}</i>
          </div>
        </FormItem> -->
        <Row>
          <Col :span="5"><i></i></Col>
          <Col :span="19"
            ><Button class="btn" type="primary" @click="createUuid">{{
              $t('safety.generate')
            }}</Button>
          </Col>
        </Row>
        <hr />
        <div class="verification">
          <FormItem name="JE_SMS_TIMEOUT" class="JE_SMS_TIMEOUT" :label="$t('safety.ageing')">
            <InputNumber v-model:value="formState.JE_SMS_TIMEOUT" min="0" class="myInputNumber"
              ><template #addonAfter>{{ $t('safety.second') }}</template>
            </InputNumber>
            <div class="text">
              <i>{{ $t('safety.ageingTip') }}</i>
            </div>
          </FormItem>
          <FormItem name="JE_SYS_NOTE_COUNT" class="JE_SYS_NOTE_COUNT" :label="$t('safety.times')">
            <InputNumber
              v-model:value="formState.JE_SYS_NOTE_COUNT"
              class="myInputNumber"
              :allow-clear="false"
              min="0"
              ><template #addonAfter>{{ $t('safety.time') }}</template>
            </InputNumber>
            <div class="text">
              <i>{{ $t('safety.timesTip') }}</i>
            </div>
          </FormItem>
          <FormItem name="JE_SYS_STAYTIME" class="JE_SYS_STAYTIME" :label="$t('safety.loginTime')">
            <InputNumber
              v-model:value="formState.JE_SYS_STAYTIME"
              class="myInputNumber"
              :allow-clear="false"
              min="-1"
              ><template #addonAfter>{{ $t('safety.hour') }}</template>
            </InputNumber>
            <div class="text">
              <i>{{ $t('safety.loginTimeTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            name="OPEN_ANTI_SQL_INJECTION"
            class="OPEN_ANTI_SQL_INJECTION interval"
            :label="$t('safety.sqlInjection')"
          >
            <Select
              v-model="formState.OPEN_ANTI_SQL_INJECTION"
              :allow-clear="false"
              :default-value="formState.OPEN_ANTI_SQL_INJECTION"
              :options="selectList"
              class="myInput"
              @change="(e) => handleChange(e, 'OPEN_ANTI_SQL_INJECTION')"
            >
            </Select>
            <div class="text">
              <i>{{ $t('safety.sqlInjectionTip') }}</i>
            </div>
          </FormItem>
          <FormItem
            name="OPEN_ANTI_XSS_ATTACK"
            class="OPEN_ANTI_XSS_ATTACK interval"
            :label="$t('safety.xssAttack')"
          >
            <Select
              v-model="formState.OPEN_ANTI_XSS_ATTACK"
              :allow-clear="false"
              :default-value="formState.OPEN_ANTI_XSS_ATTACK"
              :options="selectList"
              class="myInput"
              @change="(e) => handleChange(e, 'OPEN_ANTI_XSS_ATTACK')"
            >
            </Select>
            <div class="text">
              <i>{{ $t('safety.xssAttackTip') }}</i>
            </div>
          </FormItem>
        </div>
      </Form>
    </div>
  </div>
</template>

<script>
  import { Input, Form, Button, InputNumber, Select, Modal } from '@jecloud/ui';
  import { Row, Col } from 'ant-design-vue';
  import { onMounted, onUnmounted, reactive, ref, watch } from 'vue';
  import { useOpenDialog } from '@/hooks';
  import VueEvent from '@/helper/model/event';
  import { saveConfigData } from '@/api';
  import { onScroll, scrollToTop } from '@/utils/utils';
  import { uuid } from '@jecloud/utils';
  import { useI18n } from '@common/locales';
  const useForm = Form.useForm;
  export default {
    name: 'SecurityConfig',
    components: {
      Form,
      FormItem: Form.Item,
      Input,
      Button,
      TextArea: Input.TextArea,
      InputNumber,
      Select,
      Row,
      Col,
    },
    props: {
      dataAll: {
        type: Array,
        default: () => [],
      },
    },
    setup(props) {
      // 表单数据
      let formState = reactive({
        JE_SYS_ENCRYPT: '1',
        JE_SYS_ENCRYPT_FIELD: 'tableCode,funcCode,j_query',
        JE_SYS_ENCRYPT_KEY1: '6c652dbd93f8cfeef2a8',
        // JE_SYS_ENCRYPT_KEY2: '26178b3135de441a19ec',
        // JE_SYS_ENCRYPT_KEY3: 'a4f1c68f0fc0a4cbba49',
        JE_SMS_TIMEOUT: '60',
        JE_SYS_NOTE_COUNT: '20',
        JE_SYS_STAYTIME: '168',
        OPEN_ANTI_SQL_INJECTION: '0',
        OPEN_ANTI_XSS_ATTACK: '0',
      });
      // 对比项
      let meta = {};
      let res = {};
      // 回显数据获取
      const changeDataType = (parame) => {
        res = parame.filter((item) => {
          return item.key === 'SecurityConfig';
        });
        res[0]?.items.find((item) => {
          if (item.value && item.code === 'JE_SYS_LOGINFO' && !Array.isArray(item.value)) {
            item.value = item.value.split(',');
          }
          formState[item.code] = item['value'];
        });
        meta = JSON.parse(JSON.stringify(formState));
      };
      changeDataType(props.dataAll);

      const dataCallback = (data) => {
        changeDataType(data);
      };
      // 回显数据与原先数据是否一致的判断.
      const isChange = function () {
        return Object.keys(meta).every((item) => {
          return meta[item] === formState[item];
        });
      };
      // 保存（返回）
      const isSaveCallback = () => {
        if (isChange()) return changeBar();
        useOpenDialog({
          attribute: 'security-config',
          allFields: JSON.stringify(formState),
        });
      };

      // 生成uuid
      const createUuid = () => {
        formState.JE_SYS_ENCRYPT_KEY1 = uuid(24);
        // formState.JE_SYS_ENCRYPT_KEY2 = uuid();
        // formState.JE_SYS_ENCRYPT_KEY3 = uuid();
      };
      // 当加密传输为是密钥不能为空
      const isSecretKey = () => {
        return formState.JE_SYS_ENCRYPT === '1' && !formState.JE_SYS_ENCRYPT_KEY1;
      };
      const I18n = useI18n()?.messages.zh_CN;
      const selectList = reactive([
        { value: '1', label: I18n.yes },
        {
          value: '0',
          label: I18n.no,
        },
      ]);

      // 修改数据
      const handleChange = (e, code) => {
        formState[code] = e;
      };

      // 全局保存事件回调
      const clickCallback = () => {
        if (!isChange()) {
          if (isSecretKey()) return Modal.alert('请先生成随机密钥', 'error');
          saveConfigData({
            attribute: 'security-config',
            allFields: JSON.stringify(formState),
            type: '',
          }).then(
            (meta = JSON.parse(JSON.stringify(formState))),
            Modal.notice('保存成功', 'success'),
            VueEvent.emit('saveResult', isChange()),
            VueEvent.emit('changeAllData', { item: 'security-config', formState }),
          );
        } else {
          Modal.notice('无数据操作!', 'info');
        }
      };

      // 校验;
      let rulesRef = ref({
        JE_SYS_ENCRYPT_FIELD: [
          {
            required: false,
            message: 'Please input name',
          },
        ],
      });
      let flag = false;

      // 监听是与否，判断是否校验
      watch(
        () => formState.JE_SYS_ENCRYPT && formState.JE_SYS_ENCRYPT[0],
        (nv) => {
          if (nv === '1') {
            rulesRef.value = {
              JE_SYS_ENCRYPT_FIELD: [
                {
                  required: true,
                  message: '该选项为必填',
                },
              ],
            };
          } else {
            rulesRef.value = {
              JE_SYS_ENCRYPT_FIELD: [
                {
                  required: false,
                },
              ],
            };
            // 节流阀：首次不能清空验证信息，
            if (flag) {
              // 清空验证信息
              clearValidate();
            }
            flag = true;
          }
        },
        {
          immediate: true,
          deep: true,
        },
      );

      const { resetFields, validate, validateInfos, clearValidate } = useForm(formState, rulesRef, {
        // onValidate: (...args) => console.log(...args),
      });
      const onSubmit = () => {
        validate()
          .then(() => {
            // console.log(123);
          })
          .catch(() => {
            // console.log('error', err);
          });
      };

      // 保存后上级页面的处理
      const changeBar = () => {
        VueEvent.emit('saveResult', isChange());
      };
      VueEvent.on('toolbarSaveEvent', clickCallback);
      VueEvent.on('sendData', dataCallback);
      VueEvent.on('isSave', isSaveCallback);
      VueEvent.on('fadeScroll', onScroll);
      VueEvent.on('securityConfigCheck', clickCallback);
      onUnmounted(() => {
        VueEvent.off('toolbarSaveEvent', clickCallback);
        VueEvent.off('sendData', dataCallback);
        VueEvent.off('isSave', isSaveCallback);
        VueEvent.off('fadeScroll', onScroll);
        VueEvent.off('securityConfigCheck', clickCallback);
      });

      // 回滚到顶部
      onMounted(() => {
        scrollToTop();
      });

      return {
        formState,
        selectList,
        handleChange,
        createUuid,
        validateInfos,
        resetFields,
        onSubmit,
      };
    },
  };
</script>

<style lang="less" scoped>
  .security-config {
    font-size: 14px;
    color: #333333;
    .active {
      border: 1px solid red;
    }
    .transmission {
      padding: 30px 0 10px 0;
    }
    .verification {
      padding: 20px 0 80px 0;
    }
    :deep(.ant-input-affix-wrapper-disabled) {
      background-color: #ffffff;
    }
    :deep(.ant-input[disabled]) {
      color: rgba(63, 63, 63, 1);
      background-color: #ffffff;
    }
    .btn {
      margin-bottom: 20px;
    }
  }
</style>
